import {
  SafeAreaView,
  StatusBar,
  StyleSheet,
  TextInput,
  View,
  Image,
  Text,
  TouchableOpacity,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
} from 'react-native';
import {useState, useContext, useEffect} from 'react';
import {ThemeContext} from '../../components/ThemeContextProvider';
import AsyncStorage from '@react-native-community/async-storage';
import {loginApi} from '../../api/api';
import {delay} from '../../utils/utils';
import {useNavigation} from '@react-navigation/native';
import CheckStoreModal from './components/CheckStoreModal';
import { useDispatch, useSelector } from "react-redux";
import { setToken, setAppid, setStoreid } from '../../store/reducers/user'
const Login = () => {
  const {theme} = useContext(ThemeContext);
  const dispatch = useDispatch()
  const styles = StyleSheet.create({
    root: {
      height: '100%',
      width: '100%',
    },
    bannerImg: {
      flex: 2,
      height: '100%',
      resizeMode: 'cover',
    },
    container: {
      paddding: 80,
      width: 360,
      backgroundColor: theme.bgColor,
      paddingTop: 40,
    },
    title: {
      color: theme.fontColor,
      fontSize: 30,
      fontFamily: 'PingFang',
      width: '80%',
    },
    input: {
      color: theme.font2Color,
      borderColor: theme.dividerColor,
      borderWidth: 1,
      fontSize: 18,
      height: 64,
      borderRadius: 8,
      padding: 20,
      marginTop: 20,
      width: '80%',
    },
    button: {
      height: 64,
      width: '80%',
      backgroundColor: theme.primaryColor,
      marginTop: 20,
      marginBottom: 20,
      borderRadius: 8,
      alignItems: 'center',
      justifyContent: 'center',
    },
    buttonText: {
      color: theme.themeColor,
      fontSize: 20,
    },
    tips: {
      fontSize: 12,
      flexDirection: 'row',
    },
    customBtn: {
      height: 30,
      width: 100,
      borderRadius: 30,
      borderColor: theme.primaryColor,
      borderWidth: 1,
      alignItems: 'center',
      justifyContent: 'center',
      marginTop: 60,
    },
    customText: {
      color: theme.primaryColor,
    },
  });
  const [phone, setPhone] = useState('');
  const [password, setPassword] = useState('');
  const [domain, setDomain] = useState('');
  const navigation = useNavigation();
  const [storeShow, setStoreShow] = useState(false);
  // 确定登录事件
  const submitHandle = async () => {
    if (domain) {
      await AsyncStorage.setItem('domain', domain);
      await delay(50);
    }
    if (phone && password) {
      try {
        const {data} = await loginApi({phone, password});
        const {store_num, token, app_id, store_id} = data;
        dispatch(setToken(token))
        AsyncStorage.setItem('token', token);
        await delay(50);
        if (store_num > 1) {
          dispatch(setAppid(app_id))
          await AsyncStorage.setItem('app_id', app_id);
          setStoreShow(true);
        } else {
          dispatch(setStoreid(store_id))
          await AsyncStorage.setItem('store_id', store_id);
          navigation.replace('Cashier');
        }
      } catch {
        err => {
          console.log(err, '登录失败');
        };
      }
    }
  };
  return (
    <SafeAreaView style={styles.root}>
      <StatusBar barStyle={'dark-content'} />
      <View style={{display: 'flex', height: '100%', flexDirection: 'row'}}>
        <Image
          source={{
            uri: 'https://xiaochengxu-1259248756.cos.accelerate.myqcloud.com/uploads/905443394/20241121/VFed5A80VrVF7OE9.png',
          }}
          style={styles.bannerImg}></Image>
        <ScrollView style={styles.container} keyboardDismissMode="on-drag">
          <KeyboardAvoidingView
            style={{width: '100%', alignItems: 'center'}}
            behavior={Platform.OS == 'ios' ? 'padding' : 'height'}>
            <Text style={styles.title}>登录</Text>
            <TextInput
              style={styles.input}
              value={phone}
              onChangeText={setPhone}
              placeholder="请输入登录账号"
              cursorColor={theme.primaryColor}
              keyboardType='number-pad'
              maxLength={13}></TextInput>
            <TextInput
              style={styles.input}
              value={password}
              onChangeText={setPassword}
              placeholder="请输入密码"
              cursorColor={theme.primaryColor}
              secureTextEntry={true}
              ></TextInput>
            <TextInput
              style={styles.input}
              value={domain}
              onChangeText={setDomain}
              placeholder="品牌码(选填)"></TextInput>
            <TouchableOpacity
              activeOpacity={0.8}
              style={styles.button}
              onPress={submitHandle}>
              <Text style={styles.buttonText}>登录</Text>
            </TouchableOpacity>

            <View style={styles.tips}>
              <Text style={{color: theme.font2Color}}>登录即表示同意</Text>
              <Text style={{color: theme.primaryColor}}>《用户协议》</Text>
              <Text style={{color: theme.font2Color}}>和</Text>
              <Text style={{color: theme.primaryColor}}>《隐私声明》</Text>
            </View>
            <View style={styles.customBtn}>
              <Text style={styles.customText}>联系客服</Text>
            </View>
            <Text style={{marginTop: 30, color: theme.font2Color}}>
              版本号 V2.0
            </Text>
          </KeyboardAvoidingView>
        </ScrollView>
      </View>
      {storeShow && (
        <CheckStoreModal
          show={storeShow}
          setShow={setStoreShow}></CheckStoreModal>
      )}
    </SafeAreaView>
  );
};
export default Login;
